﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Extensions;
using XCI.Windows.Forms;
using XCI.Windows.Helper;
using System.Windows.Forms;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraEditors.Repository;
using XCI.Windows.Extensions;

namespace XCI.Sys.Forms
{
    public partial class FrmUserEdit : FrmSysBase
    {
        private bool created;
        private SysUser model;

        public FrmUserEdit()
        {
            InitializeComponent();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keys)
        {
            return OnEsc(msg, keys, () => { EditFormEscResultCancel(); });
        }

        /// <summary>
        /// 页面初始化
        /// </summary>
        protected void InitForm()
        {
            dateEdit1.Config(SysConst.DEFAULT_DATETIME_PATTERN);
            dateEdit2.Config(SysConst.DEFAULT_DATETIME_PATTERN);

            BindRoleData();
            BindModel();
        }

        /// <summary>
        /// 设置数据对象
        /// </summary>
        /// <param name="p_created">是否新建</param>
        /// <param name="p_model">数据对象</param>
        public void SetModel(bool p_created, SysUser p_model)
        {
            created = p_created;
            model = p_model;
            Text = created ? "新建系统用户" : "修改系统用户";
            ckContinue.Visible = ckReserve.Visible = p_created;
        }

        /// <summary>
        /// 绑定数据到界面
        /// </summary>
        private void BindModel()
        {
            if (!created) //编辑
            {
                layoutPassword.Visibility = layoutConfirmPassword.Visibility = LayoutVisibility.Never;
                //编辑时读取用户拥有的角色
                model.RoleIds = RoleService.Instance.SelectListByUserId(model.Id).Select(p => p.Id).JoinString();
            }

            //控制管理员控件
            if (CurrentUser.Admin.HasValue && CurrentUser.Admin.Value)
            {
                layoutAdmin.Visibility = LayoutVisibility.Always;
                editAdmin.Checked = true;
            }
            else
            {
                layoutAdmin.Visibility = LayoutVisibility.Never;
                editAdmin.Checked = false;
            }

            WinHelper.SetFormData(layoutPanel, model);
            editName.Select();
        }

        /// <summary>
        /// 绑定角色数据
        /// </summary>
        private void BindRoleData()
        {
            var list = CurrentUser.Admin.IfTrue() ?
                RoleService.Instance.SelectList(null, CurrentUser.DeptId, true)
                : RoleService.Instance.SelectListByUserId(CurrentUser.Id);

            editRole.Properties.DataSource = list;
        }

        /// <inheritdoc />
        protected override bool ValidModel(object modelx, bool raisError = true)
        {
            if (created)
            {
                //新建用户时验证规则
                if (editPassword.Text.IsEmpty())
                {
                    MessageBoxHelper.ShowError("请输入密码");
                    return false;
                }

                if (editConfirmPassword.Text.IsEmpty())
                {
                    MessageBoxHelper.ShowError("请输入确认密码");
                    return false;
                }

                if (!editPassword.Text.Equals(editConfirmPassword.Text))
                {
                    MessageBoxHelper.ShowError("确认密码必须与密码输入一致");
                    return false;
                }
            }

            return base.ValidModel(model, raisError);
        }

        /// <summary>
        /// 保存数据对象
        /// </summary>
        private bool SaveModel()
        {
            WinHelper.GetFormData(layoutPanel, model);

            var isValid = ValidModel(model);
            if (!isValid) return false;

            if (created)
            {
                return UserService.Instance.Insert(model);
            }
            return UserService.Instance.Update(model);
        }

        /// <summary>
        /// 页面加载事件
        /// </summary>
        private void FrmRoleEdit_Load(object sender, EventArgs e)
        {
            InitForm();
        }

        private void CkContinue_CheckedChanged(object sender, EventArgs e)
        {
            ckReserve.Enabled = ckContinue.Checked;
        }

        /// <summary>
        /// 保存事件
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!SaveModel()) return;
            if (ckContinue.Checked) //连续保存
            {
                MessageBoxHelper.ShowMessage("保存成功");
                var nmodel = ckReserve.Checked ? UserService.Instance.Copy(model) : UserService.Instance.New();
                SetModel(true, nmodel);
                BindModel();
            }
            else
            {
                ResultOk();
            }
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            //如果点关闭按钮后想刷新表格就用ResultOk,不刷新用ResultCancel
            ResultOk();
            //ResultCancel();
        }

    }
}